package net.csdra.libraryborrowing.service.book;

import net.csdra.libraryborrowing.domain.book.BookInfo;
import net.csdra.libraryborrowing.domain.book.BookInfoRepository;
import net.csdra.libraryborrowing.service.user.CurrentUserInfo;
import net.csdra.libraryborrowing.util.Utils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.nio.file.AccessDeniedException;

/**
 * Created by xiaomi on 2017/10/17.
 */
@Service
public class BookInfoManageServiceImpl implements BookInfoManageService {

    @Autowired
    BookInfoRepository bookInfoRepository;
    @Autowired
    CurrentUserInfo currentUserInfo;

    @Override
    public BookInfo createBookInfo(CreateBookInfo createBookInfo) throws AccessDeniedException {
        BookInfo bookInfo = Utils.createAutoSet(BookInfo.class, currentUserInfo.get().getUserName());
        Utils.copy(createBookInfo, bookInfo);
        bookInfoRepository.save(bookInfo);
        BookInfo returnValue = new BookInfo();
        BeanUtils.copyProperties(bookInfo, returnValue);
        return returnValue;
    }

    @Override
    public BookInfo updateBookInfo(UpdateBookInfo updateBookInfo) throws AccessDeniedException {
        BookInfo bookInfo = bookInfoRepository.findOne(updateBookInfo.getId());
        Assert.notNull(bookInfo, "@找不到书籍信息！");
        Utils.updateAutoSet(bookInfo, currentUserInfo.get().getUserName());
        Utils.copy(updateBookInfo, bookInfo);
        bookInfoRepository.save(bookInfo);
        BookInfo returnValue = new BookInfo();
        BeanUtils.copyProperties(bookInfo, returnValue);
        return returnValue;
    }

    @Override
    public Page<BookInfo> getBookInfoPage(GetBookInfoPage getBookInfoPage) {
        Page<BookInfo> bookInfoPage = bookInfoRepository.findAll(new PageRequest(getBookInfoPage.getPage(), getBookInfoPage.getSize(), Sort.Direction.DESC, "lastModifiedTime"));
        return bookInfoPage;
    }

}
